import time
#decorator application
"""
常用的装饰器应用
1.日志记录
2.权限检查
3.性能测量
"""
#日志记录
def log(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} and {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log
def divide(a, b):
    return a / b

divide(10, 2)
# 输出:
# Calling divide with (10, 2) and {}
# divide returned 5.0

#2.权限检查
def check_permission(user):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if user != "admin":
                print("Permission denied")
                return
            return func(*args, **kwargs)
        return wrapper
    return decorator
@check_permission("admin")
def delete_file():
    print("File deleted")
delete_file()
# 输出:
# File deleted

#3.性能监控
#监控函数调用时间
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(2)
    print("Function finished")

slow_function()
# 输出:
# Function finished
# slow_function took 2.000X seconds